package org.springframework.test.round;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/7/26 19:58
 * @since JDK 1.8
 */
@Component
public class BeanA
{
	@Resource
	private BeanB beanB;

	public void setBeanB(BeanB beanB)
	{
		this.beanB = beanB;
	}

	// 缓存对象与 注解的映射关系
	private static Map<Class<?>, List<Object>> annotions = new HashMap<>();
	public static void main(String[] args)
	{
		Object object = new Object();

		List<Object> list = new ArrayList<>();
		//循环所有的字段
		Field[] fields = object.getClass().getFields();
		for (Field field : fields)
		{
			Autowired annotation = field.getAnnotation(Autowired.class);
			list.add(annotation);
		}
		// 循环所有的方法
		Method[] methods = object.getClass().getMethods();
		for (Method method : methods)
		{
			Autowired annotation = method.getAnnotation(Autowired.class);
			list.add(annotation);
		}
		// 把对象与注解的映射加入到缓存中
		annotions.put(object.getClass(),list);
	}

	private static Map<String,Object> cacheObjects = new HashMap<>();


	public static BeanA createA() {
		BeanA beanA = (BeanA) cacheObjects.get("beanA");
		if (beanA != null){
			return beanA;
		}
		beanA = new BeanA();
		cacheObjects.put("beanA",beanA);
		BeanB b = createB();
		beanA.setBeanB(b);
		return beanA;
	}

	public static BeanB createB() {
		BeanB beanB = (BeanB) cacheObjects.get("beanB");
		if (beanB != null){
			return beanB;
		}
		beanB = new BeanB();
		cacheObjects.put("beanB",beanB);
		BeanA a = createA();
		beanB.setBeanA(a);
		return beanB;
	}

}

@Component
class BeanB
{
	@Resource
	private BeanA beanA;

	public void setBeanA(BeanA beanA)
	{
		this.beanA = beanA;
	}
}

